import { bus } from "/utils/core";

Component({
  data: {
    show: false,
    index: null,
    selectableList: []
  },
  props: {
    selectedServices: [],
    services: [],
    onChange: () => { }
  },
  didMount() { },
  didUpdate() { },
  didUnmount() { },
  methods: {
    onServiceHandle(obj) {
      if (obj.index === null && obj.form) {
        this.setData({
          show: true,
          index: obj.index
        })
        this.filterServiceSelecteable('BUY')
      } else if (obj.index !== null && obj.form) {
        this.setData({
          show: true,
          index: obj.index
        })
        this.filterServiceSelecteable(obj.form.freeServiceType)
        obj.form.serviceIndex = this.data.selectableList.findIndex(item => item.name === obj.form.name);
      } else if (obj.index !== null && obj.form === null) {
        this.onRemoveService(obj.index)
      }
      bus.publish('buyServiceFormInit', obj.form)
    },
    onRemoveService(index) {
      dd.confirm({
        title: '提示',
        content: '您确定要删除吗？',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        success: (result) => {
          if (result.confirm) {
            this.props.onChange({
              index,
              form: null
            });
          }
        },
      });
    },
    onServiceChange(obj) {
      if (obj.form !== null) {
        this.props.onChange({
          index: this.data.index,
          form: obj.form
        })
      }
      this.hideModal()
    },
    hideModal() {
      this.setData({
        show: false,
        index: null
      })
    },
    filterServiceSelecteable(freeServiceType) {
      let selectableList = this.props.services.filter(element => {
        return !this.props.selectedServices.find((item, index) => {
          return this.data.index === null ? (item.name === element.name && item.freeServiceType === freeServiceType) : (item.name === element.name && item.freeServiceType === freeServiceType && this.data.index != index)
        })
      })
      this.setData({
        selectableList: selectableList
      });
    }
  },
});
